/* eslint-disable no-console, no-shadow */
import path from 'path';
import webpack from 'webpack';
import express from 'express';
import graphQLHTTP from 'express-graphql';
import expressGraphQL from 'express-graphql';
import WebpackDevServer from 'webpack-dev-server';
import historyApiFallback from 'connect-history-api-fallback';
import chalk from 'chalk';
import webpackConfig from '../webpack.config';
import config from './config/environment';
import schema from './data/schema';
import { sequelize } from './data/models';
import cors from 'cors';
import { environments } from './constants';
import { User } from './data/models';
const argv = require('minimist')(process.argv.slice(2));

const isDev = (process.env.NODE_ENV !== environments.PROD.value) && !argv.production;

const getViewer = async (req) => {
  if (isDev) {
    return await User.findOne({
      where: {
        id: req.query.user || (req.user ? req.user.id : 1),
      },
    });
  }
  if (!req.user) {
    return null;
  }
  return await Account.findOne({
    where: {
      id: req.user.id,
      status: accountStatus.ACTIVE.value,
    },
  });
};

if (config.env === 'development') {
  // Launch GraphQL
  const graphql = express();
  graphql.use('/', expressGraphQL(async (req, res) => {
    const viewer = await getViewer(req);
    return ({
      schema,
      graphiql: isDev,
      context: {
        viewer,
        request: req,
      },
      pretty: isDev,
    });
  }))
  // graphql.use('/', graphQLHTTP({
  //   graphiql: true,
  //   pretty: true,
  //   schema
  // }));
  graphql.listen(config.graphql.port, () => console.log(chalk.green(`GraphQL is listening on port ${config.graphql.port}`)));

  // Launch Relay by using webpack.config.js
  const relayServer = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    proxy: {
      '/graphql': `http://localhost:${config.graphql.port}`
    },
    stats: {
      colors: true
    },
    hot: true,
    historyApiFallback: true
  });

  // Serve static resources
  relayServer.use('/', express.static(path.join(__dirname, '../build')));
  relayServer.listen(config.port, () => console.log(chalk.green(`Relay is listening on port ${config.port}`)));
} else if (config.env === 'production') {
  // Launch Relay by creating a normal express server
  const relayServer = express();
  relayServer.use(historyApiFallback());
  relayServer.use('/', express.static(path.join(__dirname, '../build')));
  relayServer.use('/graphql', graphQLHTTP({ schema }));
  relayServer.listen(config.port, () => console.log(chalk.green(`Relay is listening on port ${config.port}`)));
}
